#include <sys/select.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
//wudu add
#include <arpa/inet.h>

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
//wudu add
#include <unistd.h>

#define NOCONNECT 0
#define CONNECT   1

int tcp_port_scan(char *ip, int dst_port) {
	int sfd;
	struct sockaddr_in addr;
	struct servent *sp;
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(ip);
	addr.sin_port = htons(dst_port);
	
	if ( (sfd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ) 
		perror("socket"),exit(1);
	if ( connect(sfd, (struct sockaddr*)&addr, sizeof(addr)) < 0 ) {
		close(sfd);
		return NOCONNECT;
	} else {
		close(sfd);
		return CONNECT;
	}
}

int main( void ) {
	int start_port;
	int end_port;
	int dst_port;
	
	struct servent *sp;
	char ip[20];
	printf("请输入IP(0.0.0.0):");
	scanf("%s", ip);
	
	printf("输入开始端口:");
	scanf("%d", &start_port);
	printf("输入结束端口:");
	scanf("%d", &end_port);
	
	for ( dst_port=start_port; dst_port<=end_port; dst_port++) {
		if ( tcp_port_scan(ip, dst_port) == CONNECT ) {
			sp=getservbyport(htons(dst_port), "tcp");
			printf("%5d %-20s\n", dst_port, (sp==NULL)?"unkown":sp->s_name);
		}
	}
	printf("按任意键继续...\n");
	getchar();
	getchar();
}

